<?php
/**
 * This file is part of Swoft.
 *
 * @link https://swoft.org
 * @document https://doc.swoft.org
 * @contact group@swoft.org
 * @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
 */

namespace App\Middlewares;

use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Swoft\Bean\Annotation\Bean;
use Swoft\Http\Message\Middleware\MiddlewareInterface;
use App\Models\Entity\MUserapi;
use App\Models\Entity\MUserext;

/**
 * Class MerchantSubmitMiddleware - Custom middleware
 * @Bean()
 * @package App\Middlewares
 */
class MerchantSubmitMiddleware implements MiddlewareInterface
{
    /**
     * @param \Psr\Http\Message\ServerRequestInterface $request
     * @param \Psr\Http\Server\RequestHandlerInterface $handler
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \InvalidArgumentException
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        \Jpay\Helper\wk_monolog(['msg' => '头日志', 'data' => ['get' => $request->getUri()->getQuery(), 'post' => $request->raw(), 'ip' => $request->getHeaderLine('X-Real-IP')]], 'merchant/submit');

        // before request handle
        if (date('His') >= '235930' || date('His') <= '000030') {
            throw new \Exception('当前为系统对账维护时间', 444);
        }

        $inputData = $request->input();

        if (empty($inputData['userid']) || empty($inputData['orderid']) || empty($inputData['shoptype']) || empty($inputData['account']) || empty($inputData['amount']) || empty($inputData['corp']) || empty($inputData['province']) || empty($inputData['ordertime']) || empty($inputData['vstr'])) {
            throw new \Exception('必要参数为空', 501);
        }

        // if (!is_numeric($inputData['userid']) || strpos($inputData['userid'], '.')) {
        if (!\Jpay\Helper\checkformat($inputData['userid'], 'int')) {
            throw new \Exception('参数不正确', 502);
        }

        // if (!is_numeric($inputData['shoptype']) || strpos($inputData['shoptype'], '.') || !in_array($inputData['shoptype'], \config('JPAY_SHOPTYPE_LIST'))) {
        if (!\Jpay\Helper\checkformat($inputData['shoptype'], 'int') || !in_array($inputData['shoptype'], \config('JPAY_SHOPTYPE_LIST'))) {
            throw new \Exception('参数不正确', 502);
        }

        if (!is_numeric($inputData['amount']) || $inputData['amount'] <= 0) {
            throw new \Exception('参数不正确', 502);
        }

        if (!isset($inputData['orderid']) || !preg_match('/^[0-9a-zA-Z]{3,32}$/', $inputData['orderid'])) {
            throw new \Exception('参数不正确', 502);
        }

        if (!preg_match('/^0[0-9]{2,3}-[0-9]{7,8}$|^1[3-9][0-9]{9,9}$/', $inputData['account'])
            && !preg_match('/^0[0-9]{2,3}-[A-Za-z0-9@._-]{5,20}$/', $inputData['account'])
            && !preg_match('/^[0-9]{6,11}$/', $inputData['account'])
            && !preg_match('/^[0-9]{15,20}$/', $inputData['account'])) {
            throw new \Exception('参数不正确', 502);
        }

        // if (!filter_var($inputData['ordertime'], FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '/^[0-9]{4}(\-|\/)[0-9]{1,2}(\\1)[0-9]{1,2}(|\s+[0-9]{1,2}(|:[0-9]{1,2}(|:[0-9]{1,2})))$/')))) {
        if (!\Jpay\Helper\checkformat($inputData['ordertime'], 'datetime')) {
            throw new \Exception('参数不正确', 502);
        }

        if (!in_array($inputData['userid'], [94,20019]) && (abs(bcsub(time(), strtotime($inputData['ordertime']), 0))) > 600) {
            throw new \Exception('下单时间与服务器时间相差10分钟以上', 503);
        }

        // 比对运营商
        $corp = base64_decode(str_replace(' ','+', $inputData['corp']));
        if (empty($corp)) $corp = $inputData['corp'];
        $province = base64_decode(str_replace(' ','+', $inputData['province']));
        if (empty($province)) $province = $inputData['province'];
        // 针对内蒙古、黑龙江特殊处理
        // $province = substr($province, 0, 6);
        // $province = mb_substr($province, 0, 2, 'UTF-8');

        if ($inputData['shoptype'] < 20 && $inputData['userid'] != 4) {
            if (in_array(substr($inputData['account'],0,3), array('134','135','136','137','138','139','147','150','151','152','157','158','159','178','182','183','184','187','188','198'))) $corp2 = '移动';
            else if (in_array(substr($inputData['account'],0,3), array('130','131','132','145','155','156','175','176','185','186','166'))) $corp2 = '联通';
            else if (in_array(substr($inputData['account'],0,3), array('133','153','173','177','180','181','189','199'))) $corp2 = '电信';
            if ($corp2 != $corp) {
                throw new \Exception('传入运营商与号码运营商不匹配', 502);
            }
        }

        $response = $handler->handle($request);

        // after request handle

        return $response->withAddedHeader('Merchant-Middleware', 'OK');
    }
}
